package hongcaosp.app.android.video;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.comment.CommentFragment;
import hongcaosp.app.android.common.BaseAdapter;
import hongcaosp.app.android.common.IListView;
import hongcaosp.app.android.common.PresenterListener;
import hongcaosp.app.android.login.UserToken;
import hongcaosp.app.android.modle.bean.IUser;
import hongcaosp.app.android.modle.bean.IVideo;
import hongcaosp.app.android.search.SearchActivity;
import hongcaosp.app.android.user.UserDetailActivity;
import hongcaosp.app.android.user.dynamic.DynamicHolder;
import hongcaosp.app.android.user.qrcode.QRScanActivity;
import hongcaosp.app.android.video.player.PagerPlayerManager;
import hongcaosp.app.android.video.player.PlayCountListener;
import hongcaosp.app.android.video.player.PlayVideoManager;
import hongcaosp.app.android.video.player.VideoHolder;
import hongcaosp.app.android.video.player.VideoPresenter;
import xlj.lib.android.base.component.BaseFragment;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.utils.ScreenUtils;

public class MainFragment extends BaseFragment implements IListView<IVideo> ,VideoHolder.VideoClickListener,VisiblePage {
    private RecyclerView recyclerView;

    private PagerPlayerManager pagerPlayerManager;

    private VideoPresenter videoPresenter;

    private BaseAdapter<IVideo> videoPagerAdapter;

    private MaterialRefreshLayout swipeRefreshLayout;

    private boolean showFull;

    @Override
    public void initView() {
        showFull = ScreenUtils.getScreenHeight(getContext()) * 9  <= 16 * ScreenUtils.getScreenWidth(getContext());
//        if (ScreenUtils.checkDeviceHasNavigationBar(getContext())) {
//            showFull = true;
//        }
        this.recyclerView = findViewById(R.id.recycler_view);
        swipeRefreshLayout = findViewById(R.id.swipe_fresh);
        videoPagerAdapter = new BaseAdapter<IVideo>() {
            @NonNull
            @Override
            public VideoHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                VideoHolder videoHolder  =new VideoHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_shortvideo,
                        parent, false), getContext(), MainFragment.this);
                videoHolder.setVideoClickListener(MainFragment.this);
                videoHolder.setFillScreen(showFull);
                return videoHolder;
            }
        };
        pagerPlayerManager = new PagerPlayerManager(this.recyclerView,getContext());

        findViewById(R.id.btn_scan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QRScanActivity.toActivity(getContext());
            }
        });

        findViewById(R.id.btn_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(),SearchActivity.class);
                startActivity(intent);
            }
        });

        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mLayoutView.getLayoutParams();
        if (showFull) {
            lp.bottomMargin = 0;
        } else {
            lp.bottomMargin = (int) getResources().getDimension(R.dimen.tab_height);
        }
        mLayoutView.setLayoutParams(lp);

        recyclerView.setAdapter(videoPagerAdapter);

        VideoHolder.setPlayCountListener(new PlayCountListener() {
            @Override
            public void onPlay(int videoId) {
                if (videoPresenter != null) {
                    videoPresenter.postVideoPlayCount(videoId);
                }
            }
        });
        DynamicHolder.setPlayCountListener(new PlayCountListener() {
            @Override
            public void onPlay(int videoId) {
                if (videoPresenter != null) {
                    videoPresenter.postVideoPlayCount(videoId);
                }
            }
        });

        videoPresenter = new VideoPresenter(this);
        swipeRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                videoPresenter.freshData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                videoPresenter.loadMore();
            }
        });
        if (videoPresenter != null) {
            videoPresenter.freshData();
        }


    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(VideoEvent videoEvent) {
        if (videoEvent.type == 1) {
            //关注状态更新
            if (videoPagerAdapter.getItemCount() <= 0) return;
            List<IVideo> data = videoPagerAdapter.getData();
            for (int i = 0;i < data.size(); i ++) {
                IVideo v = data.get(i);
                if (v.getAuthor().getUserId() == videoEvent.user.getUserId()) {
                    IUser user = v.getAuthor();
                    user.setMeFollowTa(videoEvent.user.meFollowTa());
                    VideoHolder vh = (VideoHolder) recyclerView.findViewHolderForAdapterPosition(i);
                    if (vh != null) {
                        vh.freshUserFlag();
                    }
                }
            }
        } else if (videoEvent.type == 2) {
            //转发成功
            if (videoPagerAdapter.getItemCount() <= 0) return;
            List<IVideo> data = videoPagerAdapter.getData();
            for (int i = 0;i < data.size(); i ++) {
                IVideo v = data.get(i);
                if (v.getVid() == videoEvent.video.getVid()) {
                    v.setForwardCounts(videoEvent.video.getForwardCounts());
                    VideoHolder vh = (VideoHolder) recyclerView.findViewHolderForAdapterPosition(i);
                    vh.freshForwords();
                    break;
                }
            }
        }
    }

    @Override
    public void onHide() {
        super.onHide();
        Window window =  getActivity().getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        PlayVideoManager.getInstance().onHide(this);
    }

    @Override
    public void onShow() {
        super.onShow();
        Window window =  getActivity().getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        PlayVideoManager.getInstance().onShow(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PlayVideoManager.getInstance().destroy(this);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.fragment_main;
    }

    @Override
    public void freshList(List<IVideo> data, boolean canLoadMore) {
        videoPagerAdapter.setData(data);
        videoPagerAdapter.notifyDataSetChanged();
        swipeRefreshLayout.finishRefresh();
        swipeRefreshLayout.setLoadMore(canLoadMore);
    }

    @Override
    public void addList(List<IVideo> data, boolean canLoadMore) {
        videoPagerAdapter.addData(data);
        videoPagerAdapter.notifyDataSetChanged();
        swipeRefreshLayout.finishRefreshLoadMore();
        swipeRefreshLayout.setLoadMore(canLoadMore);
    }

    @Override
    public void onUserClick(IUser user) {
        UserDetailActivity.toDetail(getContext(),user.getUserId());
    }

    @Override
    public void onShare(IVideo videoPlayer) {
        ShareUI shareUI = new ShareUI(getContext(),videoPlayer);
        shareUI.show();
    }

    @Override
    public void onLike(final IVideo videoPlayer,final VideoHolder videoHolder) {
        if (UserToken.getDefault().isLogged(getContext())) {
            if (videoPresenter != null) {
                videoPresenter.likeVideo(videoPlayer, new PresenterListener() {
                    @Override
                    public void onSuccess() {
                        videoHolder.freshLike();
                    }

                    @Override
                    public void onFail(String message) {
                        ToastManager.getInstance().showToast(message);
                    }
                });
            }
        }
    }

    @Override
    public void unLike(final IVideo videoPlayer, final VideoHolder videoHolder) {
        if (UserToken.getDefault().isLogged(getContext())) {
            if (videoPresenter != null) {
                videoPresenter.cancelikeVideo(videoPlayer, new PresenterListener() {
                    @Override
                    public void onSuccess() {
                        videoHolder.freshLike();
                    }

                    @Override
                    public void onFail(String message) {
                        ToastManager.getInstance().showToast(message);
                    }
                });
            }
        }
    }

    @Override
    public void onFollow(IVideo videoPlayer, final VideoHolder videoHolder) {
        if (UserToken.getDefault().isLogged(getContext())) {
            if (videoPresenter != null) {
                videoPresenter.followUser(videoPlayer.getAuthor(), new PresenterListener() {
                    @Override
                    public void onSuccess() {
                        videoHolder.freshUserFlag();
                    }

                    @Override
                    public void onFail(String message) {
                        ToastManager.getInstance().showToast(message);
                    }
                });
            }
        }
    }

    @Override
    public void unFollow(IVideo videoPlayer, final VideoHolder videoHolder) {
        if (UserToken.getDefault().isLogged(getContext())) {
            if (videoPresenter != null) {
                videoPresenter.cancelFollowUser(videoPlayer.getAuthor(), new PresenterListener() {
                    @Override
                    public void onSuccess() {
                        videoHolder.freshUserFlag();
                    }

                    @Override
                    public void onFail(String message) {
                        ToastManager.getInstance().showToast(message);
                    }
                });
            }
        }
    }

    @Override
    public void onComment(IVideo videoPlayer, final VideoHolder videoHolder) {
        if (UserToken.getDefault().isLogged(getContext())) {
            CommentFragment commentFragment = new CommentFragment();
            commentFragment.setVideo(videoPlayer);
            commentFragment.setOnCommentListener(new CommentFragment.OnCommentListener() {
                @Override
                public void onCommentCount() {
                    if (videoHolder != null) {
                        videoHolder.freshComment();
                    }
                }
            });
            commentFragment.show(getFragmentManager(), "");
        }
    }
}
